<?php

namespace App\Http\Imports\Pro;

use App\Models\Department;
use App\Models\Dic;
use App\Models\Employee;
use App\Models\MaterialCategory;
use App\Models\Material;
use App\Models\Position;
use App\Models\Shift;
use App\Repositories\EmployeeRepository;
use App\Repositories\UserRepository;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Facades\Hash;


/**
 * @property UserRepository $user
 * @property EmployeeRepository $repository
 * @author sunkaiyuan
 */
class EmployeeImport implements ToCollection
    {
    /**
     * @param Collection $collection
     */
    public function __construct(EmployeeRepository $repository, UserRepository $user)
        {
        $this->repository = $repository;
        $this->user       = $user;
        }

    public function collection(Collection $collection)
        {

        set_time_limit(0);
        $collection->filter(function ($v, $k)
            {
            if ($k == 0) {
                return;
                }
            // 工号1	姓名2	性别3	籍贯4	身份证号5	户籍地6	现居地7	部门8	岗位9	班次10	
            $code     = $v['0'];
            $name     = $v['1'];
            $sex_name = $v['2'];
            $sex_id   = 0;
            if (isNotEmpty(trim($sex_name))) {
                $sex_m = Dic::whereCode("sex")->whereName($sex_name)->first();
                if ($sex_m) {
                    $sex_id = $sex_m->key;
                    }
                else {
                    fail("{$sex_name}性别不存在！");
                    }
                }
            $household_register = $v['3'];
            $idcard             = $v['4'];
            $address            = $v['5'];
            $live_address       = $v['6'];
            $department_name    = $v['7'];
            $dept_m             = Department::whereName($department_name)->first();
            if ($dept_m) {
                $department_id = $dept_m->id;
                }
            else {
                fail("{$department_name}部门不存在！");
                }

            $position_name = $v['8'];
            $posi_m        = Position::whereName($position_name)->first();
            if ($posi_m) {
                $position_id = $posi_m->id;
                }
            else {
                fail("{$position_name}岗位不存在！");
                }
            $shift_name = $v['9'];
            $shift_m    = Shift::whereName($shift_name)->first();
            if ($shift_m) {
                $shift_id = $shift_m->id;
                }
            else {
                fail("{$shift_name}班次不存在！");
                }
            // 电话11	开启账号12	婚姻13 已育14	学历15	专业16	银行卡17	开户行18	计件工资19	紧急联系人20
            $phone         = $v['10'];
            $en_account    = $v['11'] == "是" ? "1" : '0';
            $marriage_name = $v['12'];
            $marriage_id   = 0;
            if (isNotEmpty(trim($marriage_name))) {
                $marriage_m = Dic::whereCode("Marriage")->whereName($marriage_name)->first();
                if ($marriage_m) {
                    $marriage_id = $marriage_m->key;
                    }
                else {
                    fail("{$marriage_name}性别不存在！");
                    }
                }
            $children_name = $v['13'];
            $children_id   = 0;
            if (isNotEmpty(trim($children_name))) {
                $children_m = Dic::whereCode("Children")->whereName($children_name)->first();
                if ($children_m) {
                    $children_id = $children_m->key;
                    }
                else {
                    fail("{$children_name}性别不存在！");
                    }
                }

            $education_name = $v['14'];
            $education_id   = 0;
            if (isNotEmpty(trim($education_name))) {
                $education_m = Dic::whereCode("Education")->whereName($education_name)->first();
                if ($education_m) {
                    $education_id = $education_m->key;
                    }
                else {
                    fail("{$education_name}性别不存在！");
                    }
                }
            $major             = $v['15'];
            $bank_card         = $v['16'];
            $bank              = $v['17'];
            $piece_rate_salary = isEmpty($v['18']) ? 0 : $v['18'];
            $contactor         = $v['19'];

            //联系人关系21	联系人电话22	入职日期23	介绍人24	试用期25	试用薪资26	合同到期27	基本工资28	绩效29	交通补贴30
            $contactor_relation_name = $v['20'];
            $contactor_relation_id   = 0;
            if (isNotEmpty(trim($contactor_relation_name))) {
                $relation_m = Dic::whereCode("Relation")->whereName($contactor_relation_name)->first();
                if ($relation_m) {
                    $contactor_relation_id = $relation_m->key;
                    }
                else {
                    fail("{$contactor_relation_name}性别不存在！");
                    }
                }
            $contactor_phone     = $v['21'];
            $entry_date          = $v['22'];
            $introducer          = $v['23'];
            $probationary_period = $v['24'];
            $probationary_salary = isEmpty($v['25']) ? 0 : $v['25'];
            $contract_end_date   = $v['26'];
            $base_salary         = isEmpty($v['27']) ? 0 : $v['27'];
            $perf_based_salary   = isEmpty($v['28']) ? 0 : $v['28'];
            $traffic_subsidies   = isEmpty($v['29']) ? 0 : $v['29'];

            //通讯补贴31	住房补贴32	其他补贴33	社保个人%34	社保公司%35 公积金个人%36	公积金公司%37
            $communication_subsidies = isEmpty($v['30']) ? 0 : $v['30'];
            $housing_subsidies       = isEmpty($v['31']) ? 0 : $v['31'];
            $other_subsidies         = isEmpty($v['32']) ? 0 : $v['32'];
            $security_person         = isEmpty($v['33']) ? 0 : $v['33'];
            $security_company        = isEmpty($v['34']) ? 0 : $v['34'];
            $fund_person             = isEmpty($v['35']) ? 0 : $v['35'];
            $fund_company            = isEmpty($v['36']) ? 0 : $v['36'];
            $this->save([
                'attachments'             => [],
                'communication_subsidies' => $communication_subsidies,
                'housing_subsidies'       => $housing_subsidies,
                'other_subsidies'         => $other_subsidies,
                'security_person'         => $security_person,
                'security_company'        => $security_company,
                'fund_person'             => $fund_person,
                'fund_company'            => $fund_company,

                'contactor_relation_id'   => $contactor_relation_id,
                'contactor_phone'         => $contactor_phone,
                'entry_date'              => $entry_date,
                'introducer'              => $introducer,
                'probationary_period'     => $probationary_period,
                'probationary_salary'     => $probationary_salary,
                'contract_end_date'       => $contract_end_date,
                'base_salary'             => $base_salary,
                'perf_based_salary'       => $perf_based_salary,
                'traffic_subsidies'       => $traffic_subsidies,

                'phone'                   => $phone,
                'en_account'              => $en_account,
                'marriage_id'             => $marriage_id,
                'children_id'             => $children_id,
                'education_id'            => $education_id,
                'major'                   => $major,
                'bank_card'               => $bank_card,
                'bank'                    => $bank,
                'piece_rate_salary'       => $piece_rate_salary,
                'contactor'               => $contactor,

                'code'                    => $code,
                'name'                    => $name,
                'sex_id'                  => $sex_id,
                'household_register'      => $household_register,
                'idcard'                  => $idcard,
                'address'                 => $address,
                'live_address'            => $live_address,
                'department_id'           => $department_id,
                'position_id'             => $position_id,
                'shift_id'                => $shift_id,
            ]);
            });

        }
    public function save($data)
        {
        //开启账号
        $user_data = null;
        if ($data['en_account'] == 1) {
            $user_data       = $this->createUser($data);
            $data['user_id'] = $user_data->id;
            }
        else {
            $this->user->whereId($data['user_id'] ?? 0)->first()?->delete();
            }
        $employee_data = $this->repository->autosave($data);

        if ($user_data) {
            $user_data->employee_id = $employee_data->id;
            $user_data->save();
            }
        }
    private function createUser($data)
        {
        $user_id = $data['user_id'] ?? 0;
        //用户名为空，取姓名
        $username = isEmpty($data['username'] ?? "") ? $data['name'] : $data["username"];
        $this->user->withTrashed()->whereUsername($username)->get()->filter(function ($item) use ($user_id)
            {
            if ($item->id != $user_id)
                fail("开启的账号登录名重复！请手动设置登录用户名！");
            else {
                if ($item->trashed()) {
                    $item->restore();
                    }
                }
            });

        //密码为空，取手机后六位
        $password = isEmpty($data['password'] ?? "") ? substr($data['phone'], -6) : $data["password"];
        $newdata  = [
            'id'            => $user_id,
            'name'          => $data['name'],
            'username'      => $username,
            'sex_id'        => $data['sex_id'],
            'phone'         => $data['phone'],
            'department_id' => $data['department_id'],
            'attachments'   => $data['attachments'],
            'password'      => Hash::make($password)
        ];

        return $this->user->autosave($newdata);
        }
    }
